package com.gcb.controller.company;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import com.gcb.common.annotation.Log;
import com.gcb.common.core.domain.AjaxResult;
import com.gcb.common.core.domain.R;
import com.gcb.common.core.domain.entity.GcbUser;
import com.gcb.common.core.domain.entity.SysDept;
import com.gcb.common.core.domain.entity.SysUser;
import com.gcb.common.core.page.TableDataInfo;
import com.gcb.common.enums.BusinessType;
import com.gcb.common.enums.AuthStatusEnum;
import com.gcb.common.enums.CommonStatusEnum;
import com.gcb.common.enums.CreateTypeEnum;
import com.gcb.common.utils.StringUtils;
import com.gcb.common.utils.poi.ExcelUtil;
import com.gcb.controller.BaseController;
import com.gcb.domain.dto.*;
import com.gcb.domain.entity.Company;
import com.gcb.domain.entity.CompanyUser;
import com.gcb.domain.vo.company.CompanyVO;
import com.gcb.domain.vo.company.CompanyPageListVo;
import com.gcb.service.ICompanyService;
import com.gcb.framework.service.ISysDeptService;
import com.gcb.framework.service.ISysUserService;
import com.gcb.framework.utils.SecurityUtils;
import com.gcb.service.ICompanyUserService;
import com.gcb.service.IGcbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

/**
 * 企业信息Controller
 *
 * @author seh
 * @date 2024-03-08
 */
@RestController
@RequestMapping("/company/manage")
public class CompanyController extends BaseController {

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private ICompanyUserService companyUserService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private IGcbUserService gcbUserService;

    /**
     * 查询企业信息列表
     */
    @PreAuthorize("@ss.hasPermi('company:manage:list')")
    @GetMapping("/list")
    public TableDataInfo list(CompanyListSearchDTO company) {
        startPage();
        List<CompanyPageListVo> list = companyService.selectCompanyList(company);
        return getDataTable(list);
    }

    /**
     * 导出企业信息列表
     */
    @PreAuthorize("@ss.hasPermi('company:manage:export')")
    @Log(title = "企业信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CompanyListSearchDTO company) {
        List<CompanyPageListVo> list = companyService.selectCompanyList(company);
        ExcelUtil<CompanyPageListVo> util = new ExcelUtil<>(CompanyPageListVo.class);
        util.exportExcel(response, list, "企业信息数据");
    }

    /**
     * 获取企业信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('company:manage:query')")
    @GetMapping(value = "/query/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        Company company = companyService.selectCompanyById(id);
        if (Objects.isNull(company)) {
            return AjaxResult.success();
        }

        CompanyVO companyDetailVo = BeanUtil.copyProperties(company, CompanyVO.class);
        //转义状态
        companyDetailVo.setAuthStatusStr(AuthStatusEnum.getInfo(companyDetailVo.getAuthStatus()));
        companyDetailVo.setWaterStatusStr(AuthStatusEnum.getInfo(companyDetailVo.getWaterStatus()));
        companyDetailVo.setStatusStr(CommonStatusEnum.getInfoByCode(companyDetailVo.getStatus()));
        companyDetailVo.setSignTypeStr(CreateTypeEnum.getInfo(companyDetailVo.getSignType()));
        companyDetailVo.setCity(company.getCity());
        //查询超管
        CompanyUser leader = companyUserService.getLeaderByCompanyId(id);
        if (Validator.isNotNull(leader)) {
            GcbUser user = gcbUserService.selectGcbUserById(leader.getUserId());
            if (Validator.isNotNull(user)) {
                companyDetailVo.setUserName(user.getName());
                companyDetailVo.setPhonenumber(user.getMobile());
            }
        }
        //查询创建人
        Long createBy = company.getCreateBy();
        Integer signType = company.getSignType();
        if (Validator.isNotNull(createBy) && Validator.equal(CreateTypeEnum.OPERATION.getCode(), signType)) {
            SysUser creatorUser = sysUserService.selectUserById(createBy);
            if (Validator.isNotNull(creatorUser)) {
                companyDetailVo.setCreatorName(creatorUser.getUserName());
                companyDetailVo.setCreatorPhone(creatorUser.getPhonenumber());
            }
        }
        //查询运营商
        Long operateId = company.getOperateId();
        companyDetailVo.setOperateId(operateId);
        if (Validator.isNotNull(operateId)) {
            SysDept sysDept = sysDeptService.selectDeptById(operateId);
            if (Validator.isNotNull(sysDept)) {
                companyDetailVo.setDeptName(sysDept.getDeptName());
            }
        }
        return success(companyDetailVo);
    }

    /**
     * 新增企业信息
     */
    @PreAuthorize("@ss.hasPermi('company:manage:add')")
    @Log(title = "企业信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Company company) {
        return toAjax(companyService.insertCompany(company, SecurityUtils.getUserId()));
    }

    /**
     * 修改企业信息
     */
    @PreAuthorize("@ss.hasPermi('company:manage:edit')")
    @Log(title = "企业信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Company company) {
        return toAjax(companyService.updateCompany(company));
    }

    /**
     * 批量更新企业状态
     */
    @PreAuthorize("@ss.hasPermi('company:manage:edit')")
    @PostMapping("/updateStatus")
    public AjaxResult updateStatus(@RequestBody UpdateCompanyStatusDto dto) {
        Long userId = SecurityUtils.getUserId();
        return toAjax(companyService.batchUpdateCompanyStatus(dto, userId));
    }

    /**
     * 删除企业信息
     */
    @PreAuthorize("@ss.hasPermi('company:manage:remove')")
    @Log(title = "企业信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(companyService.deleteCompanyByIds(ids));
    }

    /**
     * 转移系统超级管理员
     */
    @PreAuthorize("@ss.hasPermi('company:manage:edit')")
    @PostMapping("/transferCompanySuperAdmin")
    public AjaxResult transferCompanySuperAdmin(@RequestBody TransferCompanySuperAdminDto dto) {
        Long userId = SecurityUtils.getUserId();
        return toAjax(companyService.transferCompanySuperAdmin(dto, userId));
    }


    /**
     * 退出企业
     */
    @PreAuthorize("@ss.hasPermi('company:manage:edit')")
    @PostMapping("/leaveCompany")
    public AjaxResult leaveCompany(@RequestBody CompanyUserSaveDTO dto) {
        Long userId = SecurityUtils.getUserId();
        return toAjax(companyService.leaveCompany(dto, userId));
    }


    /**
     * 更换企业用户角色
     */
    @PreAuthorize("@ss.hasPermi('company:manage:edit')")
    @PostMapping("/user/role/edit")
    public AjaxResult changeCompanyUserRole(@RequestBody CompanyUserSaveDTO dto) {
        Long userId = SecurityUtils.getUserId();
        return toAjax(companyService.changeCompanyUserRole(dto, userId));
    }


    /**
     * 获取企业下拉列表
     *
     * @param status
     */
    @PreAuthorize("@ss.hasPermi('company:manage:list')")
    @GetMapping("/getCompanyListByOperator")
    public AjaxResult getCompanyListByOperator(@RequestParam(name = "status", defaultValue = "1") Integer status) {
        return success(companyService.getCompanyListByOperator(status));
    }

    @PostMapping("/list/all")
    public R<List<CompanyPageListVo>> getAllCompany(@RequestBody CompanyListSearchDTO company){
        List<CompanyPageListVo> list = companyService.selectCompanyList(company);
        return R.ok(list);
    }

}
